/* Copyright 2007 Gearbox Software - http://www.gearboxsoft.com
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
     http:www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.*/
namespace GearBlog.Web.Filters
{
	using System;
	using Castle.MonoRail.Framework;
	using GearBlog.Web.Models;
	using GearBlog.Web.Utils;

	public enum BlogAccessType
	{
		Comment,
		Reader
	}

	public class BlogAccessFilterAttribute : FilterAttribute
	{
		private BlogAccessType _accessType;
		private Type _authenticationAgentType;

		public BlogAccessFilterAttribute(BlogAccessType accessType, Type authenticationAgentType)
			: base(ExecuteEnum.BeforeAction, typeof (BlogAccessFilter))
		{
			_accessType = accessType;
			_authenticationAgentType = authenticationAgentType;
		}

		public BlogAccessType AccessType
		{
			get { return _accessType; }
		}
		public Type AuthenticationAgentType
		{
			get { return _authenticationAgentType; }
			set { _authenticationAgentType = value; }
		}
	}

	public class BlogAccessFilter : Filter, IFilterAttributeAware
	{
		private BlogAccessFilterAttribute _filterAttribute;

		public FilterAttribute Filter
		{
			set { _filterAttribute = (BlogAccessFilterAttribute) value; }
		}

		protected override bool OnBeforeAction(IRailsEngineContext context, Controller controller)
		{
			bool requireLogin = false;
			if (_filterAttribute.AuthenticationAgentType!=null) SecurityUtil.SetAuthenticationAgent(_filterAttribute.AuthenticationAgentType);
			Setting setting = Setting.FindFirst();
			switch (_filterAttribute.AccessType)
			{
				case (BlogAccessType.Comment):
					requireLogin = setting.RegisteredUserCommentOnly;
					break;
				case (BlogAccessType.Reader):
					requireLogin = setting.RegisteredUserOnly;
					break;
			}

			if (requireLogin)
			{
				if (SecurityUtil.GetCurrentUser(context) == null)
					return SecurityUtil.AttemptLogin(controller, context.Url);
				else
					return true;
			}
			else
				return true;
		}
	}
}